﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using System.Text.RegularExpressions;
using System.Text;

namespace HostAssistantCore
{
    class RewriteTranslator
    {
        //private static string posturl = "http://www.htaccesstowebconfig.com";//免费在线转换地址
        private static string posturl = "http://cbsa.com.br/tools/online-convert-htaccess-to-web-config.aspx";//免费在线转换地址
        private static string solidstr = "__VIEWSTATE=%2FwEPDwUKMTQ1NjAzNDA2NmRkda0g%2BfM0T1BspsHkjH294BE%2FWw4KGn5duVRO%2FxtM56s%3D&__VIEWSTATEGENERATOR=CA0B0334&__EVENTVALIDATION=%2FwEdAAOOt041bR9emSUOrenRU8sOsiEMikfqxcx1nOQxwn%2BULouorNtI3sHxdtRPlcdEQm8LllWzc7RtJW%2FiyTvAF5XAhAKRv9tXqfHra7WYYsgmXw%3D%3D&txtInput=";//固定参数
        private static string solidstr_left = "------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"__EVENTTARGET\"\r\n\r\n\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"__EVENTARGUMENT\"\r\n\r\n\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"__VIEWSTATE\"\r\n\r\n/wEPDwUKMTM2ODg0NDMzNGRk4hMNiG5sz5UWOjEMzGhxyRbQWqc=\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"__VIEWSTATEGENERATOR\"\r\n\r\nF19DD350\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"__SCROLLPOSITIONX\"\r\n0\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"__SCROLLPOSITIONY\"\r\n1000\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"__PREVIOUSPAGE\"\r\n\r\n9Dt0PY2gRtM001-KviZZnmNBAfOax0CBWYs0pUCP4Bm6gEaZLJzzeZ-ac-CDyeLFCca806PfwwzIld-fe8E3X1v5P2vmNGGeRSxI0eUFv-uWT-5o0\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"ctl00$cphContent$txtInput\"\r\n\r\n";//固定参数
        private static string solidstr_right = "\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"ctl00$cphContent$btnConvert\"\r\n\r\nConvert to Web.Config\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"ctl00$cphContent$txtName\"\r\n\r\n\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"ctl00$cphContent$fupFile\"; filename=\"\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI\r\nContent-Disposition: form-data; name=\"ctl00$cphContent$txtText\"\r\n\r\n\r\n------WebKitFormBoundary12Zj41uoPBjkJhAI--";//固定参数
        private static string txtInput_regex = "[<]textarea[^id]*id[^cphContent_txtResult]*cphContent_txtResult[^>]*>[^<]*[<]/textarea>";
        private static string form_data_path = System.Environment.CurrentDirectory + "\\form_data_path.txt";//存储form_data临时文件
        private static string btnConvert = "&btnConvert=Convert+to+Web.Config   ";//固定参数

        #region 在线转换一
        /// <summary>
        /// --
        /// </summary>
        /// <param name="htaccess_path">伪静态文件</param>
        private static void OnlineTranslate(string htaccess_path)
        {
            //string htaccess_rewrite = "RewriteRule ^index.html$ http://www.yoursite.com/ [R=301,L]";//伪静态规则
            string htaccess_rewrite = "";//伪静态规则
            bool rewrite_translate_flag = true;//转义成功标志
            /* ==== 读取伪静态规则 ==== */
            if (File.Exists(htaccess_path))
            {
                try
                {
                    htaccess_rewrite = File.ReadAllText(htaccess_path);
                }
                catch
                {

                }
            }
            string parameters = solidstr + System.Web.HttpUtility.UrlEncode(htaccess_rewrite) + btnConvert;//组合参数
            string rewrite_result = "";//转换结果
            string pre_webconf_rewrite = PostTranslate(parameters);//.Replace("\r\n","")//通过网络请求拿到转换结果
            /* ==== 通过正则拿到html内容 ==== */
            Regex reg = new Regex("[<]textarea[^id]*id[^txtResult]*txtResult[^>]*>[^<]*[<]/textarea>");
            Match matches = reg.Match(pre_webconf_rewrite);
            foreach (var match in matches.Groups)
            {
                rewrite_result = match.ToString();
            }
            /* ==== //通过正则拿到html内容 ==== */
            /* ==== 去除html标签 ==== */
            if (rewrite_result != "" && rewrite_result.Contains("txtResult"))
            {
                try
                {
                    rewrite_result = rewrite_result.Substring(rewrite_result.IndexOf(">") + 1, rewrite_result.LastIndexOf("</textarea>") - rewrite_result.IndexOf(">") - 1);
                    if (rewrite_result.StartsWith("\r\n"))
                    {
                        rewrite_result = rewrite_result.Substring(2);
                    }
                }
                catch
                {
                    rewrite_result = "";
                }
            }
            else
            {
                rewrite_translate_flag = false;
            }
            /* ==== //去除html标签 ==== */
            /* ==== 转换html转义字符 ==== */
            if (rewrite_result != "")
            {
                rewrite_result = HtmlTranslate(rewrite_result);
            }
            else
            {
                rewrite_translate_flag = false;
            }
            /* ==== //转换html转义字符 ==== */
            if (rewrite_result != "")
            {
                /* ==== 写入文本 ==== */
                string webconf_path = "d:\\web.conf";
                File.WriteAllText(webconf_path, rewrite_result);
                /* ==== //写入文本 ==== */
            }
            else
            {
                rewrite_translate_flag = false;
            }
        }
        #endregion

        #region 在线转换二
        /// <summary>
        /// --
        /// </summary>
        /// <param name="htaccess_path">伪静态文件</param>
        /// <param name="store_path">存储路径</param>
        public static string OnlineTranslate_Q(string htaccess_path)
        {
            /* ==== 伪静态规则 ==== */
            string htaccess_rewrite = "";
            /* ==== 读取伪静态规则 ==== */
            if (File.Exists(htaccess_path))
            {
                try
                {
                    htaccess_rewrite = File.ReadAllText(htaccess_path);
                }
                catch
                {
                    return "";
                }
            }
            /* ==== //读取伪静态规则 ==== */
            /* ==== init param ==== */
            string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("X") + "y"; //http random split
            solidstr_left = solidstr_left.Replace("WebKitFormBoundary12Zj41uoPBjkJhAI", boundary.Substring(4));//更换boundary
            solidstr_right = solidstr_right.Replace("WebKitFormBoundary12Zj41uoPBjkJhAI", boundary.Substring(4));//更换boundary
            string poststr = solidstr_left + htaccess_rewrite + solidstr_right;//组合参数
            /* ==== 存储到目标文本 ==== */
            File.WriteAllText(form_data_path, poststr);
            string rewrite_result = "";//转换结果
            string pre_webconf_rewrite = HttpTranslate(posturl, boundary);//通过网络请求拿到转换结果
            if (!pre_webconf_rewrite.Contains("Your Web.config"))//常规判断
            {
                return "";
            }
            /* ==== 通过正则拿到html内容 ==== */
            Regex reg = new Regex(txtInput_regex);
            Match matches = reg.Match(pre_webconf_rewrite);
            foreach (var match in matches.Groups)
            {
                rewrite_result = match.ToString();
            }
            /* ==== //通过正则拿到html内容 ==== */
            /* ==== 去除html标签 ==== */
            if (rewrite_result != "" && rewrite_result.Contains("txtResult"))
            {
                try
                {
                    rewrite_result = rewrite_result.Substring(rewrite_result.IndexOf(">") + 1, rewrite_result.LastIndexOf("</textarea>") - rewrite_result.IndexOf(">") - 1);
                    if (rewrite_result.StartsWith("\r\n"))
                    {
                        rewrite_result = rewrite_result.Substring(2);
                    }
                }
                catch
                {
                    rewrite_result = "";
                }
            }
            else
            {
                return "";
            }
            /* ==== //去除html标签 ==== */
            /* ==== 转换html转义字符 ==== */
            if (rewrite_result != "")
            {
                rewrite_result = HtmlTranslate(rewrite_result);
            }
            else
            {
                return "";
            }
            /* ==== //转换html转义字符 ==== */
            if (rewrite_result != "")
            {
                /* ==== 写入文本 ==== */
                //File.WriteAllText(webconf_path, rewrite_result);
                return rewrite_result;
                /* ==== //写入文本 ==== */
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 转换Html转义字符
        private static string HtmlTranslate(string input)
        {
            input = input.Replace("&nbsp;", " ");//空格
            input = input.Replace("&lt;", "<");//小于
            input = input.Replace("&gt;", ">");//大于
            input = input.Replace("&amp;", "&");//&
            input = input.Replace("&quot;", "\"");//引号
            input = input.Replace("&copy;", "©");//copy
            input = input.Replace("&reg;", "®");//reg
            input = input.Replace("&times;", "×");//乘
            input = input.Replace("&divide;", "÷");//除
            return input;
        }
        #endregion

        #region 发送Post请求获取返回结果
        private static string PostTranslate(string Parameters)
        {
            string search_result = "";
            try
            {
                search_result = WgetHttpPage(posturl, Parameters);//发送POST
            }
            catch
            {

            }
            return search_result;//返回结果
        }
        #endregion

        #region Http模拟form-data请求
        private static string HttpTranslate(string url, string boundary)
        {
            /* ==== 设置参数 ==== */
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;//cookie
            request.AllowAutoRedirect = true;//redirect
            request.Method = "POST";//type
            request.Timeout = 30000;
            //string boundary = DateTime.Now.Ticks.ToString("X");//random split
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;//contenttype
            /* ==== 获取字节 ==== */
            FileStream fs = new FileStream(form_data_path, FileMode.Open, FileAccess.Read);
            byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, bArr.Length);//读取文本信息
            fs.Close();
            /* ==== 存储字节到字节流 ==== */
            Stream postStream = request.GetRequestStream();
            postStream.Write(bArr, 0, bArr.Length);
            postStream.Close();
            /* ==== 发送请求并获取相应回应数据 ==== */
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            //返回结果网页html代码
            string content = sr.ReadToEnd();
            return content;
        }
        #endregion

        #region 发送POST请求
        /// <summary>
        /// 发送Post
        /// </summary>
        /// <param name="strUrl"></param>
        /// <param name="strParam"></param>
        /// <returns></returns>
        private static string WgetHttpPage(string strUrl, string strParam)
        {
            string strResult = "";
            try
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                System.Net.HttpWebRequest req = (HttpWebRequest)(WebRequest.Create(strUrl));
                byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(strParam);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = requestBytes.Length;
                req.Timeout = 30000;
                Stream requestStream = req.GetRequestStream();
                requestStream.Write(requestBytes, 0, requestBytes.Length);
                requestStream.Close();
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.UTF8);
                strResult = System.Convert.ToString(sr.ReadToEnd());
                sr.Close();
                res.Close();
                return strResult;
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 委托验证方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="certificate"></param>
        /// <param name="chain"></param>
        /// <param name="errors"></param>
        /// <returns></returns>
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
        #endregion
    }
}
